/*
 * connexions.c
 *
 *  Created on: 5 nov. 2013
 *      Author: julien
 */

#include <stdarg.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <resolv.h>
#include <errno.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdlib.h>

#include "../include/echo_client.h"
#include "../include/connexions_c.h"

#define BACKLOG 1024

int create_conn(int port, int* ip){
	int sockfd;
	struct sockaddr_in dest;

	/*---Create the socket---*/

	if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
		perror("Socket");
		exit(EXIT_FAILURE);
	}

	/*---Initialize server address/port struct---*/
		memset(&dest, '\0', sizeof(dest));
		dest.sin_family = AF_INET;
		dest.sin_port = htons(port);
		inet_aton(ip, &dest.sin_addr);

		/*---Connect to server---*/
		if (connect(sockfd, (struct sockaddr *) &dest, sizeof(struct sockaddr))
				< 0) {
			perror("Connect");
			exit(EXIT_FAILURE);
		}

		return sockfd;
}

/* Create the listening socket */
void create_socket(char* ip, int *port, int* Socket) {
	int listening_socket;
	struct sockaddr_in servaddr; // socket address struct

	if ((listening_socket = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
		perror("socket");
		exit(EXIT_FAILURE);
	}

	int on = 1;
	int status = setsockopt(listening_socket, SOL_SOCKET, SO_REUSEADDR, &on,
			sizeof(on));

	/* Set all bytes in socket address structure to
	 zero, and fill in the relevant data members */

	memset(&servaddr, 0, sizeof(servaddr));
	servaddr.sin_addr.s_addr = htonl((ulong)ip);
	servaddr.sin_family = AF_INET;
	servaddr.sin_port = 0;

	/* Bind our socket addresss to the
	 listening socket, and call listen() */

	if (bind(listening_socket, (struct sockaddr *) &servaddr, sizeof(servaddr))
			< 0) {
		perror("bind");
		exit(EXIT_FAILURE);
	}

	//max = listening_socket;

	/* Wait for a connection, then accept() it */

	if (listen(listening_socket, BACKLOG) < 0) {
		perror("listen");
		exit(EXIT_FAILURE);
	}

	*Socket = listening_socket;
	*port = servaddr.sin_port;

}
